import axios from 'axios';
import { queue } from 'async';
import _ from 'lodash';

// 记录每个symbol的最后请求时间
const symbolLastRequest = new Map();
const REQUEST_INTERVAL = 3 * 60 * 1000; // 3分钟限制间隔

// 创建串行队列，确保预测API调用按顺序执行
const predictQueue = queue(function (task, callback) {
    predictSymbol(...task.args)
        .then(result => callback(null, result))
        .catch(error => {
            console.error('队列处理预测失败:', error);
            callback(error);
        });
}, 1);

/**
 * 调用预测API
 * @param {string} symbol - 交易对符号，如 'BRUSDT'
 * @param {string} interval - K线间隔，如 '3m'
 * @param {number} historyLength - 历史数据长度，如 120
 * @param {string} endTime - 结束时间，如 '2025-08-27 13:45'
 * @returns {Promise} hybrid_action值
 */
async function predictSymbol(symbol, interval, historyLength, endTime) {
    const now = Date.now();
    const lastRequest = symbolLastRequest.get(symbol);

    // 检查频率限制
    if (lastRequest && (now - lastRequest) < REQUEST_INTERVAL) {
        const remainingTime = Math.ceil((REQUEST_INTERVAL - (now - lastRequest)) / 1000 / 60);
        console.log(`${symbol} 请求过于频繁，需等待 ${remainingTime} 分钟`);
        return null;
    }

    try {
        console.log(`发起预测API请求: ${symbol} ${endTime}`);
        const response = await axios.post('http://127.0.0.1:8001/predict', {
            symbol,
            interval,
            history_length: historyLength,
            n_predictions: 32,
            end_time: endTime
        }, {
            headers: {
                'Content-Type': 'application/json'
            }
        });

        const hybridAction = response.data?.data?.hybrid_prediction?.hybrid_action;
        const signal = response.data?.data?.trading_signal_evaluation?.operation_recommendation?.signal;
        // 记录请求时间
        symbolLastRequest.set(symbol, now);
        return {
          action: _.includes(['STRONG_TRADE', 'MODERATE_TRADE', 'WEAK_TRADE'], signal) ? hybridAction: signal + '_' + hybridAction,
          take_profit_percent: response.data?.data?.conservative_stop_levels?.conservative_levels?.take_profit_percent,
          stop_loss_percent: response.data?.data?.conservative_stop_levels?.conservative_levels?.stop_loss_percent
        };
    } catch (error) {
        console.error('预测API调用失败:', error);
        throw error;
    }
}

/**
 * 通过队列串行调用预测API
 * @param {string} symbol
 * @param {string} interval
 * @param {number} historyLength
 * @param {string} endTime
 * @param {Promise|function} onSuccess - 成功回调函数或Promise，接收预测结果作为参数
 * @returns {Promise}
 */
function queuePredict(symbol, interval, historyLength, endTime, onSuccess) {
    // 如果队列长度大于1，直接返回null，避免队列积压
    if (predictQueue.length() > 1) {
        console.log('预测队列积压，跳过本次请求');
        return Promise.resolve(null);
    }

    return new Promise((resolve, reject) => {
        predictQueue.push({ args: [symbol, interval, historyLength, endTime] }, async (error, result) => {
            if (error) {
                reject(error);
            } else {
                try {
                    if (onSuccess) {
                        if (typeof onSuccess === 'function') {
                            await onSuccess(result);
                        } else if (onSuccess && typeof onSuccess.then === 'function') {
                            await onSuccess;
                        }
                    }
                    resolve(result);
                } catch (callbackError) {
                    reject(callbackError);
                }
            }
        });
    });
}

export default {
    queuePredict,
    predictSymbol
}
